package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param employee
     * @param session
     * @return
     */
        @PostMapping("/login")
    public R<Employee> login( @RequestBody Employee employee, HttpSession session ) {
        //判断数据不能为空
        if (employee == null ||
                StringUtils.isEmpty(employee.getUsername()) ||
                StringUtils.isEmpty(employee.getPassword())
        ) {
            return R.error("用户或密码不能为空");
        }
        //不为空的话调用数据库查询
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername, employee.getUsername());
        Employee employeeServiceOne = employeeService.getOne(lqw);
        if (employee == null) {
            return R.error("账号不存在");
        }
        //账号存在比较密码
        String password = employeeServiceOne.getPassword();//数据库密码带密文
        String password1 = employee.getPassword();//用户输入的密码,不带密文
        String s = DigestUtils.md5DigestAsHex(password1.getBytes());
        if (password.equals(s)) {
            //对比成功,返回
            employeeServiceOne.setPassword(null);
            session.setAttribute("loginUser", employeeServiceOne);
            return R.success(employeeServiceOne);
        }
            if(employeeServiceOne.getStatus() == 0){
                return R.error("账号已禁用");
            }
        return R.error("用户名或密码错误");
    }

    /**
     * 退出
     * @return
     */
    @PostMapping("/logout")
    public R<Employee> logout(HttpSession httpSession){
        //清除session中的数据
        httpSession.removeAttribute("loginUser");
        return R.success(null);
    }
    /**
     * 添加员工
     */
    @PostMapping
    public  R saveEmployee(@RequestBody Employee employee,HttpSession session){
     /*   //判断用户名是否重复
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper();
        qw.eq(Employee::getUsername,employee.getUsername());
        Employee one = employeeService.getOne(qw);
        if (one!=null){
            return R.error("y用户名已存在!!");
        }*/
        //0.检查数据,那些是需要处理的
        //0.1密码进行mdk5加密
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        //0.2.status不需要处理,默认就是1
        //0.3.创建和修改时间设置为当前时间
      /*  employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        //0.4.创建人和修改人应该是当前人的ID
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        employee.setCreateUser(loginUser.getId());
        employee.setUpdateUser(loginUser.getId());*/
        //1.调用业务层保存employee数据
        boolean save = employeeService.save(employee);
        //2.返回结果
        if (save){
            return R.success(null);
        }else {
            return R.error("保存失败");
        }
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R pageQuery(Integer page,Integer pageSize,String name){
      // 进行带参数的分页查询
        IPage<Employee> pageInfo =new Page<>(page,pageSize);
        LambdaQueryWrapper<Employee> qw =new LambdaQueryWrapper<>();
        //封装查询条件
        if (StringUtils.isNotEmpty(name)){
            qw.like(Employee::getName,name);
        }
        employeeService.page(pageInfo,qw);//分页参数,查询条件
        //通过pageInfo对象获取分页结果 1.List<>集合 2.总记录数
        List<Employee> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        Map data =new HashMap();
        data.put("records",records);
        data.put("total",total);
        return R.success(data);

    }

    /**
     * 修改状态
     * @param session
     * @param employee
     * @return
     */
    @PutMapping
    public R updateEmplouee( @RequestBody Employee employee ,HttpSession session){
 /*       log.info(employee.toString());
        Employee loginUser = (Employee) session.getAttribute("loginUser");
        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser(loginUser.getId());*/
        boolean b = employeeService.updateById(employee);
        if (b){
            return R.success(null);
        }
        return R.error("修改失败");
    }

    /**
     * 修改员工信息
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> getById(@PathVariable Long id){
        log.info("根据id查询员工信息");
        Employee employee = employeeService.getById(id);
        if (employee!=null){
            return R.success(employee);
        }
        return R.error("没有查询到对应员工信息");
    }
}
